package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

// 定时任务管理，订单超时自动取消，派送超时自动取消
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    //订单超时自动取消
    @Scheduled(cron = "0 * * * * ?")
    //@Scheduled(cron = "1/5 * * * * ?")
    public void orderOutTIme(){
        log.info("查询超时订单，当前时间为：{}",LocalDateTime.now());
        //查询超时订单
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.selectByStatusAndOrderTime(Orders.PENDING_PAYMENT, time);

        //判断超时订单是否为空
        if (ordersList != null && !ordersList.isEmpty()){
            //更新订单状态
            for (Orders order : ordersList) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("用户未付款，订单超时");
                orderMapper.update(order);
            }



        }
    }

    //点单派送超时
    @Scheduled(cron = "0 0 1 * * ?")
    //@Scheduled(cron = "0/5 * * * * ?")
    public void orderDeliveryOutTime(){
        log.info("更新派送订单：{}",LocalDateTime.now());
        //更新派送订单
        LocalDateTime time = LocalDateTime.now().plusHours(-1);
        List<Orders> ordersList = orderMapper.selectByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, time);

        //判断超时订单是否为空
        if (ordersList != null && !ordersList.isEmpty()){
            //更新订单状态
            for (Orders order : ordersList) {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            }
        }

    }

}
